#include "CCodeProfiler.h"
#include <fstream>
using namespace std;

CCodeProfiler::CCodeProfiler( void )
{
	QueryPerformanceFrequency( &m_LIFreq ); 
}
void CCodeProfiler::StartTimer( void )
{
	QueryPerformanceCounter( &m_LIStartingTime  ); 
}
void CCodeProfiler::EndTimer( void )
{
	QueryPerformanceCounter( &m_LIEndingTime  );
}
void CCodeProfiler::ResultOfTime( string FunctName )
{
	EndTimer( );
	TotalResults* total = new TotalResults();
	double result = ( double( ( m_LIEndingTime.QuadPart  - m_LIStartingTime.QuadPart ) / ( float )m_LIFreq.QuadPart ) );

	if( m_vResultsTotal.empty() )
	{
		total->SetFunctName( FunctName );
		total->SetCount( 1 );
		total->SetTotals(  result );
		total->GetResults()->push_back( result );
		m_vResultsTotal.push_back( total );
	}
	else
	{
		for( unsigned int i = 0 ; i < m_vResultsTotal.size() ; ++i )
		{
			if(  (*m_vResultsTotal[i]).GetFunctName() == FunctName  )
			{
				m_vResultsTotal[ i ]->SetCount( m_vResultsTotal[ i ]->GetCount() + 1 );
				(*m_vResultsTotal[i]).GetResults()->push_back( result );
				m_vResultsTotal[ i ]->SetTotals( m_vResultsTotal[ i ]->GetTotals() + result );
				return;
			}
		}
		total->SetFunctName( FunctName );
		total->SetCount( 1 );
		total->GetResults()->push_back( result );
		total->SetTotals(  result ); 
		this->m_vResultsTotal.push_back( total );
	}
}

void CCodeProfiler::SaveResults( void )
{
	fstream out;
	char timeBuffer[ 40 ];
	char buffer[ 40 ];
	char fileBuffer[ 80 ];
	const tm*  dateStamp;
	time_t  CurTime;
	CurTime = time( 0 );
	dateStamp = localtime( &CurTime );
	strftime(timeBuffer,40,"%d %B %Y %I:%M:%S %p",dateStamp);
	for( UINT i = 0 ; i < m_vResultsTotal.size(); ++i )
	{
		sprintf_s( fileBuffer,"%s.txt", m_vResultsTotal[ i ]->GetFunctName().c_str());
		out.open( fileBuffer , ios::out | ios::app );
		out << timeBuffer << "\n";

		double average = m_vResultsTotal[ i ]->GetTotals() / m_vResultsTotal[ i ]->GetCount();
		out << "Function Name : " << m_vResultsTotal[ i ]->GetFunctName() << "\n"; 
		for( int j = 0 ; j < m_vResultsTotal[ i ]->GetCount()  ; ++j )
		{
			sprintf(buffer, "Time %d: %f", j + 1, m_vResultsTotal[i]->GetResultsData( j ) );
			out << buffer << "\n";
		}
		out << "Number of Runs : " << m_vResultsTotal[ i ]->GetCount() << "\n"; 
		out << "Average Time : " << average << "\n";
		out << "\n";

		out.close();
	}

	m_vResultsTotal.clear();
}
